﻿using Inaction.ServiceContract;
using System.IO;

namespace Inaction.Extensions.Zip
{
    public class ZipHelper : IZip
    {
        public byte[] Compress(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (var gzip = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(ms))
                {
                    gzip.Write(bytes, 0, bytes.Length);
                    gzip.Flush();
                    gzip.Close();
                    ms.Close();
                    return ms.ToArray();
                }
            }
        }

        public byte[] Decompress(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                var buf = new byte[4096];
                using (var gzip = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(new MemoryStream(bytes)))
                {
                    int count = 0;
                    do
                    {
                        count = gzip.Read(buf, 0, buf.Length);
                        if (count > 0) ms.Write(buf, 0, count);
                    }
                    while (count > 0);
                    gzip.Flush();
                    gzip.Close();
                    ms.Close();
                    return ms.ToArray();
                }
            }
        }
    }
}
